﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using HR60_PanelSoft.Tools;
using HR60_PanelSoft.View.Base;
using HR60_PanelSoft.View.TabForms;
using System.ComponentModel;

namespace HR60_PanelSoft.View.Controls
{
	/// <summary>
	/// 单选按钮
	/// 在同一BaseForm或BaseFormContrl下，且id相同的Radio视为一组
	/// </summary>
	public class FormRadioButton : BaseFormControl
	{
		RadioButton radio = new RadioButton();

		bool autoChangeFlag = false;

		[Browsable(true)]
		public event EventHandler CheckedChanged;
		
		public FormRadioButton()
		{
			this.AutoSize = true;
			this.Margin = new System.Windows.Forms.Padding(0);
			this.Size = new System.Drawing.Size(12, 12);
			this.Controls.Add(radio);
			radio.CheckedChanged += new EventHandler(radio_CheckedChanged);
		}

		/// <summary>
		/// 显示的文本
		/// </summary>
		[Browsable(true)]
		[Description("标题"), Category("String"), DefaultValue("标题")]
		public string Title
		{
			get
			{
				return radio.Text;
			}
			set
			{
				radio.Text = value;
			}
		}

		/// <summary>
		/// 是否选中
		/// </summary>
		[Browsable(true)]
		[Description("是否选中"), Category("Boolean"), DefaultValue(false)]
		public bool Checked
		{
			get
			{
				return this.radio.Checked;
			}
			set
			{
				this.radio.Checked = value;
			}
		}

		void radio_CheckedChanged(object sender, EventArgs e)
		{
			// 若联动改变则跳过
			if (!autoChangeFlag)
			{
				// 查找同组的radio
				BaseFormControl parent = findParentFormControl();
				BaseForm form = findForm();

				IList<BaseFormControl> list = new List<BaseFormControl>();
				if (parent != null)
				{
					list = parent.findChildFormControls(Id);
				}
				else if (form != null)
				{
					list = form.findChildFormControls(Id);
				}

				// 取消其他radio选择
				foreach (BaseFormControl f in list)
				{
					if (f.GetType().Equals(typeof(FormRadioButton)) && f != this)
					{
						((FormRadioButton)f).autoChangeSelect();
					}
				}

				// 触发valueChange
                //valueChange(this, e);
                valueChange_Normal(this, e);

			}

			if (CheckedChanged != null)
			{
				CheckedChanged(this, e);
			}
		}
		
		/// <summary>
		/// 由于同组radio选中而改为未选中状态，不触发valueChange
		/// </summary>
		protected void autoChangeSelect()
		{
			autoChangeFlag = true;
			radio.Checked = false;
			autoChangeFlag = false;
		}

		// 重写属性
		public override bool ValueEnabled
		{
			get
			{
				return radio.Checked;
			}
			set
			{
				radio.Checked = value;
			}
		}
	}
}
